<template>
  <div class="add">
    <el-card class="add-container">
      <el-form :model="courseForm" :rules="rules" ref="courseRef" label-width="100px" class="courseForm">
        <el-form-item label="课程类型" prop="coursetype">
          <el-select v-model="courseForm.coursetype" class="m-2" placeholder="请选择咨询类型" size="large">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="咨询地区" prop="teacherarea">
          <el-select v-model="courseForm.teacherarea" class="m-2" placeholder="请选择咨询地区" size="large">
            <el-option
              v-for="item in optionsd"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="咨询主题" prop="coursename">
          <el-input style="width: 300px" v-model="courseForm.coursename" placeholder="请输入课程名称"></el-input>
        </el-form-item>
        <el-form-item required label="咨询背景图" prop="courseimage">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgServer"
            accept="jpg,jpeg,png"
            :headers="{
              token: token
            }"
            :show-file-list="false"
            :before-upload="handleBeforeUpload"
            :on-success="handleUrlSuccess"
          >
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="courseForm.courseimage" :src="courseForm.courseimage" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="咨询价格" prop="courseprice">
          <el-input type="number" min="0" style="width: 300px" v-model="courseForm.courseprice" placeholder="请输入课程价格"></el-input>
        </el-form-item>
        <el-form-item label="咨询文案">
          <div ref='coursecopywriting'></div>
        </el-form-item>
        <el-form-item label="咨询收获">
          <div ref='courseharvest'></div>
        </el-form-item>
        <el-form-item label="报名信息">
          <div ref='courseinformation'></div>
        </el-form-item>
        <!-- <el-form-item label="注意事件">
          <div ref='attentionevent'></div>
        </el-form-item> -->
        
        
        <!-- <el-form-item label="上架状态" prop="coursessellstatus">
          <el-radio-group v-model="courseForm.coursessellstatus">
            <el-radio label="0">下架</el-radio>
            <el-radio label="1">上架</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="推荐状态" prop="coursesrecommend">
          <el-radio-group v-model="courseForm.coursesrecommend">
            <el-radio label="0">否</el-radio>
            <el-radio label="1">是</el-radio>
          </el-radio-group>
        </el-form-item> -->
       
        <!-- <el-form-item required label="课程副图" prop="coursesimg">
          <el-upload
            class="avatar-uploader"
            :action="uploadImgServer"
            accept="jpg,jpeg,png"
            :headers="{
              token: token
            }"
            :show-file-list="false"
            :before-upload="handleBeforeUploadImg"
            :on-success="handleUrlSuccessImg"
          >
            <img style="width: 100px; height: 100px; border: 1px solid #e9e9e9;" v-if="courseForm.coursesimg" :src="courseForm.coursesimg" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item> -->
        <el-form-item label="注意事件">
          <div ref='attentionevent'></div>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitAdd()">{{ id ? '立即修改' : '立即创建' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { reactive, ref, toRefs, onMounted, onBeforeUnmount, getCurrentInstance } from 'vue'
import WangEditor from 'wangeditor'
import axios from '@/utils/axios'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import { localGet, uploadImgServer, uploadImgsServer, hasEmoji } from '@/utils'
export default {
  name: 'Addcourse',
  setup() {
    const { proxy } = getCurrentInstance()
    // console.log('proxy', proxy)
    const attentionevent = ref(null)
    const coursecopywriting = ref(null)
    const courseharvest = ref(null)
    const courseinformation = ref(null)
    const courseRef = ref(null)
    const route = useRoute()
    const router = useRouter()
    const { id } = route.query
   
    const state = reactive({
      uploadImgServer,
      token: localGet('token') || '',
      id: id,
      courseForm: {
        coursetype: '',
        courseprice: '',
        teacherarea:'',
        // sellingprice: '',
        // coursessellstatus: '0',
        courseimage:'',
        // coursesrecommend: '0',
        // courseslecturer: ''
      },
      rules: {
        courseimage: [
          { required: 'true', message: '请上传主图', trigger: ['change'] }
        ],
  
        coursename: [
          { required: 'true', message: '请填写课程名称', trigger: ['change'] }
        ],
        teacherarea: [
          { required: 'true', message: '请选择咨询地区', trigger: ['change'] }
        ],
        courseprice: [
          { required: 'true', message: '请填写课程价格', trigger: ['change'] }
        ],
        // sellingprice: [
        //   { required: 'true', message: '请填写课程售价', trigger: ['change'] }
        // ],
        coursetype: [
          { required: 'true', message: '请填写课程类型', trigger: ['change'] }
        ],
      },
      options : [
      {
        value: 1,
        label: '团队咨询',
      },
      {
        value: 2,
        label: '心理沙龙',
      }],
      optionsd : [
      {
        value: 1,
        label: '长沙',
      },{
        value: 2,
        label: '福州',
      }]
    })
    let instance,instance1,instance2,instance3
    onMounted(() => {
        fwb(attentionevent)
        fwb1(coursecopywriting)
        fwb2(courseharvest)
        fwb3(courseinformation)
     
    })
    onBeforeUnmount(() => {
      instance.destroy()
      instance = null
      instance1.destroy()
      instance1 = null
      instance2.destroy()
      instance2 = null
       instance3.destroy()
      instance3 = null
    })
     const fwb3 = (name) => {
      instance1 = new WangEditor(name.value)
      instance1.config.showLinkImg = false
      instance1.config.showLinkImgAlt = false
      instance1.config.showLinkImgHref = false
      instance1.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
      instance1.config.uploadFileName = 'file'
      instance1.config.uploadImgHeaders = {
        token: state.token
      }
      // 图片返回格式不同，需要自定义返回格式
      instance1.config.uploadImgHooks = {
        // 图片上传并返回了结果，想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function(insertImgFn, result) {
          console.log('result', result)
          // result 即服务端返回的接口
          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          if (result.data && result.data.length) {
            result.data.forEach(item => insertImgFn(item))
          }
        }
      }
      instance1.config.uploadImgServer = uploadImgsServer
      Object.assign(instance1.config, {
        onchange() {
          console.log('change')
        },
      })
      instance1.create()
      if (id) {
        console.log(id);
        axios.get(`/consultation/${id}`).then(res => {
          // console.log(res,123);
          // const { courses, firstCategory, secondCategory, thirdCategory } = res
          // console.log('courses',courses)
          const courses = res;

          state.courseForm = {
            coursename: courses.coursename,
            courseprice: courses.courseprice,
            teacherarea: courses.teacherarea,
            // attentionevent: instance.txt.html(),
            // coursecopywriting: instance1.txt.html(),
            // courseharvest: instance2.txt.html(),

            // courseinformation: instance3.txt.html(),
            // sellingprice: courses.sellingprice,
            // coursessellstatus: String(courses.coursessellstatus),
            courseimage: proxy.$filters.prefix(courses.courseimage),
            coursetype:courses.coursetype,
            // coursesimg:proxy.$filters.prefix(courses.coursesimg),
            // coursesrecommend: String(courses.coursesrecommend),
            // courseslecturer: courses.courseslecturer
          }
          console.log(proxy.$filters.prefix(courses.courseimage)+'00');
          if (instance1) {
            // 初始化课程详情 html
            instance1.txt.html(courses.coursecopywriting)
          }
        })
      }
    }
     const fwb2 = (name) => {
      instance2 = new WangEditor(name.value)
      instance2.config.showLinkImg = false
      instance2.config.showLinkImgAlt = false
      instance2.config.showLinkImgHref = false
      instance2.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
      instance2.config.uploadFileName = 'file'
      instance2.config.uploadImgHeaders = {
        token: state.token
      }
      // 图片返回格式不同，需要自定义返回格式
      instance2.config.uploadImgHooks = {
        // 图片上传并返回了结果，想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function(insertImgFn, result) {
          console.log('result', result)
          // result 即服务端返回的接口
          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          if (result.data && result.data.length) {
            result.data.forEach(item => insertImgFn(item))
          }
        }
      }
      instance2.config.uploadImgServer = uploadImgsServer
      Object.assign(instance2.config, {
        onchange() {
          console.log('change')
        },
      })
      instance2.create()
      if (id) {
        console.log(id);
        axios.get(`/consultation/${id}`).then(res => {
          // console.log(res,123);
          // const { courses, firstCategory, secondCategory, thirdCategory } = res
          // console.log('courses',courses)
          const courses = res;

          state.courseForm = {
            coursename: courses.coursename,
            courseprice: courses.courseprice,
            teacherarea: courses.teacherarea,
            //  attentionevent: instance.txt.html(),
            // coursecopywriting: instance1.txt.html(),
            // courseinformation: instance3.txt.html(),

            // courseharvest: instance2.txt.html(),
            // sellingprice: courses.sellingprice,
            // coursessellstatus: String(courses.coursessellstatus),
            courseimage: proxy.$filters.prefix(courses.courseimage),
            coursetype:courses.coursetype,
            // coursesimg:proxy.$filters.prefix(courses.coursesimg),
            // coursesrecommend: String(courses.coursesrecommend),
            // courseslecturer: courses.courseslecturer
          }
          console.log(proxy.$filters.prefix(courses.courseimage)+'00');
          if (instance2) {
            // 初始化课程详情 html
            instance2.txt.html(courses.courseharvest)
          }
        })
      }
    }
     const fwb1 = (name) => {
      instance3 = new WangEditor(name.value)
      instance3.config.showLinkImg = false
      instance3.config.showLinkImgAlt = false
      instance3.config.showLinkImgHref = false
      instance3.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
      instance3.config.uploadFileName = 'file'
      instance3.config.uploadImgHeaders = {
        token: state.token
      }
      // 图片返回格式不同，需要自定义返回格式
      instance3.config.uploadImgHooks = {
        // 图片上传并返回了结果，想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function(insertImgFn, result) {
          console.log('result', result)
          // result 即服务端返回的接口
          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          if (result.data && result.data.length) {
            result.data.forEach(item => insertImgFn(item))
          }
        }
      }
      instance3.config.uploadImgServer = uploadImgsServer
      Object.assign(instance3.config, {
        onchange() {
          console.log('change')
        },
      })
      instance3.create()
      if (id) {
        console.log(id);
        axios.get(`/consultation/${id}`).then(res => {
          // console.log(res,123);
          // const { courses, firstCategory, secondCategory, thirdCategory } = res
          // console.log('courses',courses)
          const courses = res;

          state.courseForm = {
            coursename: courses.coursename,
            courseprice: courses.courseprice,
            teacherarea: courses.teacherarea,
            // coursecopywriting: instance1.txt.html(),

            //  attentionevent: instance.txt.html(),
            // courseharvest: instance2.txt.html(),
            // courseinformation: instance3.txt.html(),
            // sellingprice: courses.sellingprice,
            // coursessellstatus: String(courses.coursessellstatus),
            courseimage: proxy.$filters.prefix(courses.courseimage),
            coursetype:courses.coursetype,
            // coursesimg:proxy.$filters.prefix(courses.coursesimg),
            // coursesrecommend: String(courses.coursesrecommend),
            // courseslecturer: courses.courseslecturer
          }
          console.log(proxy.$filters.prefix(courses.courseimage)+'00');
          if (instance3) {
            // 初始化课程详情 html
            instance3.txt.html(courses.courseinformation)
          }
        })
      }
    }
    const fwb = (name) => {
      instance = new WangEditor(name.value)
      instance.config.showLinkImg = false
      instance.config.showLinkImgAlt = false
      instance.config.showLinkImgHref = false
      instance.config.uploadImgMaxSize = 2 * 1024 * 1024 // 2M
      instance.config.uploadFileName = 'file'
      instance.config.uploadImgHeaders = {
        token: state.token
      }
      // 图片返回格式不同，需要自定义返回格式
      instance.config.uploadImgHooks = {
        // 图片上传并返回了结果，想要自己把图片插入到编辑器中
        // 例如服务器端返回的不是 { errno: 0, data: [...] } 这种格式，可使用 customInsert
        customInsert: function(insertImgFn, result) {
          console.log('result', result)
          // result 即服务端返回的接口
          // insertImgFn 可把图片插入到编辑器，传入图片 src ，执行函数即可
          if (result.data && result.data.length) {
            result.data.forEach(item => insertImgFn(item))
          }
        }
      }
      instance.config.uploadImgServer = uploadImgsServer
      Object.assign(instance.config, {
        onchange() {
          console.log('change')
        },
      })
      instance.create()
      if (id) {
        console.log(id);
        axios.get(`/consultation/${id}`).then(res => {
          // console.log(res,123);
          // const { courses, firstCategory, secondCategory, thirdCategory } = res
          // console.log('courses',courses)
          const courses = res;
          console.log(res);
          state.courseForm = {
            coursename: courses.coursename,
            courseprice: courses.courseprice,
            teacherarea: courses.teacherarea,
            //  attentionevent: instance.txt.html(),

            // coursecopywriting: instance1.txt.html(),
            // courseharvest: instance2.txt.html(),
            // courseinformation: instance3.txt.html(),
            // sellingprice: courses.sellingprice,
            // coursessellstatus: String(courses.coursessellstatus),
            courseimage: proxy.$filters.prefix(courses.courseimage),
            coursetype:courses.coursetype,
            // coursesimg:proxy.$filters.prefix(courses.coursesimg),
            // coursesrecommend: String(courses.coursesrecommend),
            // courseslecturer: courses.courseslecturer
          }
          console.log(proxy.$filters.prefix(courses.courseimage)+'00');
          if (instance) {
            // 初始化课程详情 html
            instance.txt.html(courses.attentionevent)
          }
        })
      }
    }
    const submitAdd = () => {
      courseRef.value.validate((vaild) => {
        if (vaild) {
          // 默认新增用 post 方法
          let httpOption = axios.post
          let params = {
            courseimage: state.courseForm.courseimage,
            attentionevent: instance.txt.html(),
            coursecopywriting: instance1.txt.html(),
            courseharvest: instance2.txt.html(),
            courseinformation: instance3.txt.html(),
            coursename: state.courseForm.coursename,
            teacherarea: state.courseForm.teacherarea,
            // coursessellstatus: state.courseForm.coursessellstatus,
            courseprice: state.courseForm.courseprice,
            // sellingprice: state.courseForm.sellingprice,
            coursetype:state.courseForm.coursetype,
            // coursesimg:state.courseForm.coursesimg,
            // coursesrecommend: state.courseForm.coursesrecommend,
            // courseslecturer: state.courseForm.courseslecturer
          }
          console.log(params);
          if (params.coursename.length > 128) {
            ElMessage.error('课程名称不能超过128个字符')
            return
          }
          console.log('params', params)
          if (id) {
            params.id = id
            // 修改课程使用 put 方法
            httpOption = axios.put
          }
          httpOption('/consultation', params).then(() => {
            ElMessage.success(id ? '修改成功' : '添加成功')
            router.push({ path: '/consultation' })
          })
        }
      })
    }
    const handleBeforeUpload = (file) => {
      const sufix = file.name.split('.')[1] || ''
      if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
        ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
        return false
      }
    }
    const handleBeforeUploadImg = (file) => {
      const sufix = file.name.split('.')[1] || ''
      if (!['jpg', 'jpeg', 'png'].includes(sufix)) {
        ElMessage.error('请上传 jpg、jpeg、png 格式的图片')
        return false
      }
    }
    const handleUrlSuccess = (val) => {
      state.courseForm.courseimage = val.data || ''
    }
    // const handleUrlSuccessImg = (val) => {
    //   state.courseForm.coursesimg = val.data || ''
    // }
    return {
      ...toRefs(state),
      courseRef,
      submitAdd,
      handleBeforeUpload,
      handleUrlSuccess,
      attentionevent,
      coursecopywriting,
      courseharvest,
      courseinformation,
      handleBeforeUploadImg
    }
  }
}
</script>

<style scoped>
  .add {
    display: flex;
  }
  .add-container {
    flex: 1;
    height: 100%;
  }
  .avatar-uploader {
    width: 100px;
    height: 100px;
    color: #ddd;
    font-size: 30px;
  }
  .avatar-uploader-icon {
    display: block;
    width: 100%;
    height: 100%;
    border: 1px solid #e9e9e9;
    padding: 32px 17px;
  }
</style>